import { useMemoizedFn } from 'ahooks';
import { Switch } from 'antd';
import React, { Dispatch, useState } from 'react';
import { useContextSelector } from 'use-context-selector';

import { SvgIcon } from '@/components/icon';
import { t } from '@/locales/i18n';
import HotQuestionModal from '@/pages/app-orchestration/components/HotQuestionModal';
import InputGuideModal from '@/pages/app-orchestration/components/InputGuideModal';
import {
  defaultChatInputGuideConfig,
  defaultHotQuestionConfig,
  defaultWhisperConfig,
} from '@/pages/chat/tools/constants';
import { HotQuestion, InputGuide } from '@/store/orchestrationStore';
import { AppChatConfigType, AppDetailType, VariableItemType } from '@/types/app/type';

import { WorkflowContext } from '../../context';

import VariableEdit from './system/VariableEdit';
import WelcomeTextConfig from './system/WelcomeTextConfig';

type ComponentProps = {
  chatConfig: AppChatConfigType;
  setAppDetail: Dispatch<React.SetStateAction<AppDetailType>>;
};

function NodeUserGuide() {
  return <div className="nodrag" />;
}

export default React.memo(NodeUserGuide);

function WelcomeText({ chatConfig: { welcomeText }, setAppDetail }: ComponentProps) {
  return (
    <div className="nodrag">
      <WelcomeTextConfig
        // resize={'both'}
        value={welcomeText}
        onChange={(e) => {
          setAppDetail((state) => ({
            ...state,
            chatConfig: {
              ...state.chatConfig,
              welcomeText: e.target.value,
            },
          }));
        }}
      />
    </div>
  );
}

function ChatStartVariable({ chatConfig: { variables = [] }, setAppDetail }: ComponentProps) {
  const updateVariables = useMemoizedFn((value: VariableItemType[]) => {
    setAppDetail((state) => ({
      ...state,
      chatConfig: {
        ...state.chatConfig,
        variables: value,
      },
    }));
  });

  return <VariableEdit variables={variables} onChange={(e) => updateVariables(e)} />;
}

function QuestionGuide({ chatConfig: { questionGuide = false }, setAppDetail }: ComponentProps) {
  return (
    <div className="flex w-full items-center justify-between">
      <div className="flex items-center gap-2">
        <SvgIcon icon="rj-guess" />
        <span>{t('core.app.Question Guide')}</span>
      </div>
      <Switch
        checked={questionGuide}
        onChange={(e) => {
          const value = e;
          setAppDetail((state) => ({
            ...state,
            chatConfig: {
              ...state.chatConfig,
              questionGuide: value,
            },
          }));
        }}
      />
    </div>
  );
}

// function TTSGuide({ chatConfig: { ttsConfig }, setAppDetail }: ComponentProps) {
//   return (
//     <TTSSelect
//       value={ttsConfig}
//       onChange={(e) => {
//         setAppDetail((state) => ({
//           ...state,
//           chatConfig: {
//             ...state.chatConfig,
//             ttsConfig: e,
//           },
//         }));
//       }}
//     />
//   );
// }

function WhisperGuide({ chatConfig: { whisperConfig, ttsConfig }, setAppDetail }: ComponentProps) {
  return (
    <div className="flex w-full items-center justify-between">
      <div className="flex items-center gap-2">
        <SvgIcon icon="ic_rj_sound" />
        <span>语音</span>
      </div>
      <Switch
        className="ml-auto"
        checked={whisperConfig?.open ?? false}
        onChange={(e) => {
          setAppDetail((state) => ({
            ...state,
            chatConfig: {
              ...state.chatConfig,
              whisperConfig: {
                ...(whisperConfig || defaultWhisperConfig),
                open: !!e,
              },
            },
          }));
        }}
      />
    </div>
  );
}

// function ScheduledTrigger({
//   chatConfig: { scheduledTriggerConfig },
//   setAppDetail,
// }: ComponentProps) {
//   return (
//     <ScheduledTriggerConfig
//       value={scheduledTriggerConfig}
//       onChange={(e) => {
//         setAppDetail((state) => ({
//           ...state,
//           chatConfig: {
//             ...state.chatConfig,
//             scheduledTriggerConfig: e,
//           },
//         }));
//       }}
//     />
//   );
// }

function QuestionInputGuide({
  chatConfig: { chatInputGuide },
  setAppDetail,
  inputGuides,
}: ComponentProps & { inputGuides: InputGuide[] }) {
  const appId = useContextSelector(WorkflowContext, (v) => v.appId);
  const updateInputGuides = useContextSelector(WorkflowContext, (v) => v.updateInputGuides);
  const [isPreview, setIsPreview] = useState(false);
  const [inputGuideModalVisible, setInputGuideModalVisible] = useState(false);

  const closeInputGuideModal = () => {
    setInputGuideModalVisible(false);
  };

  const saveInputGuides = (guides: InputGuide[]) => {
    updateInputGuides(guides);
  };

  const openInputGuideModal = () => {
    setInputGuideModalVisible(true);
  };

  return appId ? (
    <div className="flex w-full items-center justify-between">
      <div className="flex items-center gap-2">
        <SvgIcon icon="ic_mail" />
        <span>{t('input_guide')}</span>
      </div>
      <span
        className={`mr-2 text-[14px] text-[#86909C] ${
          isPreview ? 'cursor-default' : 'cursor-pointer hover:text-[#1677ff]'
        }`}
        onClick={() => !isPreview && openInputGuideModal()}
      >
        已配置{inputGuides.length}个引导&gt;&gt;
      </span>
      <Switch
        className="ml-auto"
        checked={chatInputGuide?.open ?? false}
        onChange={(e) => {
          setAppDetail((state) => ({
            ...state,
            chatConfig: {
              ...state.chatConfig,
              chatInputGuide: {
                ...(chatInputGuide || defaultChatInputGuideConfig),
                open: !!e,
              },
            },
          }));
        }}
      />
      <InputGuideModal
        visible={inputGuideModalVisible}
        onClose={closeInputGuideModal}
        initialGuides={inputGuides}
        onSave={saveInputGuides}
      />
    </div>
  ) : null;
}

function HotQuestionGuide({
  chatConfig: { hotQuestionConfig },
  setAppDetail,
  hotQuestions,
}: ComponentProps & { hotQuestions: HotQuestion[] }) {
  const appId = useContextSelector(WorkflowContext, (v) => v.appId);
  const updateHotQuestions = useContextSelector(WorkflowContext, (v) => v.updateHotQuestions);
  const [isPreview, setIsPreview] = useState(false);
  const [hotQuestionModalVisible, setHotQuestionModalVisible] = useState(false);

  const closeHotQuestionModal = () => {
    setHotQuestionModalVisible(false);
  };

  const saveHotQuestions = (hotQuestions: HotQuestion[]) => {
    updateHotQuestions(hotQuestions);
  };

  const openHotQuestionModal = () => {
    setHotQuestionModalVisible(true);
  };

  return appId ? (
    <div className="flex w-full items-center justify-between">
      <div className="flex items-center gap-2">
        <SvgIcon icon="point-all" />
        <span>热门问题</span>
      </div>
      <span
        className={`mr-2 text-[14px] text-[#86909C] ${
          isPreview ? 'cursor-default' : 'cursor-pointer hover:text-[#1677ff]'
        }`}
        onClick={() => !isPreview && openHotQuestionModal()}
      >
        已配置{hotQuestions?.length}个问题&gt;&gt;
      </span>
      <Switch
        className="ml-auto"
        checked={hotQuestionConfig?.open ?? false}
        onChange={(e) => {
          setAppDetail((state) => ({
            ...state,
            chatConfig: {
              ...state.chatConfig,
              hotQuestionConfig: {
                ...(hotQuestionConfig || defaultHotQuestionConfig),
                open: !!e,
              },
            },
          }));
        }}
      />
      <HotQuestionModal
        visible={hotQuestionModalVisible}
        onClose={closeHotQuestionModal}
        initialQuestions={hotQuestions}
        onSave={saveHotQuestions}
      />
    </div>
  ) : null;
}

// function FileSelectConfig({ chatConfig: { fileSelectConfig }, setAppDetail }: ComponentProps) {
//   const onChangeNode = useContextSelector(WorkflowContext, (v) => v.onChangeNode);
//   const nodes = useContextSelector(WorkflowContext, (v) => v.nodes);
//   const workflowStartNode = nodes.find((item) => item.type === FlowNodeTypeEnum.workflowStart)!;

//   return (
//     <FileSelect
//       value={fileSelectConfig}
//       onChange={(e) => {
//         setAppDetail((state) => ({
//           ...state,
//           chatConfig: {
//             ...state.chatConfig,
//             fileSelectConfig: e,
//           },
//         }));

//         // Dynamic add or delete userFilesInput
//         const canUploadFiles = e.canSelectFile || e.canSelectImg;
//         const repeatKey = workflowStartNode?.data.outputs.find(
//           (item) => item.key === userFilesInput.key,
//         );
//         if (canUploadFiles) {
//           !repeatKey &&
//             onChangeNode({
//               nodeId: workflowStartNode.id,
//               type: 'addOutput',
//               value: userFilesInput,
//             });
//         } else {
//           repeatKey &&
//             onChangeNode({
//               nodeId: workflowStartNode.id,
//               type: 'delOutput',
//               key: userFilesInput.key,
//             });
//         }
//       }}
//     />
//   );
// }
